/*
**js基础函数H类
**黄总
**2017.3.7
*/
const path = top.require('path')
const _config = top.require(path.resolve(top.process.env.NODE_ENV === 'development' ? top.process.cwd() : path.resolve(top.process.cwd(), 'resources/app.asar'), 'config/config.js'))

//依赖layer，如果没有加载layui报错
!function (layer,globalconfig,$){
	if(null === layer){
		alert('程序依赖layer，请先加载layer.js！');
	}
	function H(){
		this.electron = top.require('electron');
		this.BrowserWindow = this.electron.remote.BrowserWindow;
		this.ipcMain = this.electron.remote.ipcMain;
		this.path = top.require('path');
		this.dirname = top.__dirname;
	}

	H.prototype.set_localStorage = function(obj,ocj){
		localStorage.setItem(obj, JSON.stringify(ocj));
	};
	H.prototype.get_localStorage = function (obj){
		obj = obj.split('.');
		//获取数据
		try {
			let data = JSON.parse(localStorage.getItem(obj[0]));
			return obj[1]?data[obj[1]]:data;
		} catch (e) {
			this.error('传参格式不正确！')
			return false
		}
	};
	H.prototype.remove_localStorage = function(obj){
		localStorage.removeItem(obj);
	};
	//设置全局request页面间传值
	H.prototype.makerequest = function(){
		var url = window.location.search;
    	var RequestUrl = {};
		if(url.indexOf("?")!=-1){
			var str = url.substr(1);　//去掉?号
			var strs = str.split("&");
			for(var i=0;i<strs.length;i++){
				console.log(strs[i].split("=")[0]);
				console.log(strs[i].split("=")[1]);
				RequestUrl[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]);
			}
		}
		var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
		//判断是否有父页面
		if(index){
			//判断是否有值
			var data = parent.$('#ajaxiframechilddate_'+index).html();
			if (undefined !== data) {
				data = JSON.parse(data);
				return data;
			}
		}
		return 	RequestUrl;
	};
	//封装ajax统一后台读取数据接口
	H.prototype.get_info_ajax = function(url,data,type,callback){	
		layer.ready(function(){ 
			var indexload = layer.load();
			$.ajax({
				type:type,
				url:Conf.domain+url,
				data:data,
				//下面这个先不做
				beforeSend: function( xhr ) {
					xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
				},
				success:function(data){
					layer.close(indexload);
					//全局判断是否登陆未登录跳出
					if (('undefined' != typeof data.isrelogin) && 1 == data.isrelogin){
						window.location.href = Conf.root+'/index.html';
					}
					data.errno > 0?data.errno == 1000?layer.msg(data.errmsg,{icon:2,time:2000}):layer.msg('请求失败！'):callback(data);
				},
				error:function(data, XMLHttpRequest, textStatus, errorThrown){  
					layer.close(indexload);
					layer.msg('网络传输失败！');
				}
			});
		});		
	};
	//随机函数
	H.prototype.ran_dome = function(m){
		m = m > 13 ? 13 : m;
		var num = new Date().getTime();
		return num.toString().substring(13 - m);
	};
	H.prototype.ajaxiframe = function(href,data,w,h,title='',no,full=0){
		//生成元素
		//看是否全屏
		full = 1 == full?full:0;
		//获取宽度高度
		w = full?'100%':w?w+'px':'auto';
		h = full?'100%':h?h+'px':'auto';
		if (no && no=='nosubmit') {
			var index = layer.open({
					type: 2,
					title:title,
					shadeClose:false,
					shade: 0.8,
					shift:2,
					area: [w, h],
					content: href, //dom
			});
		} else {
			var index = layer.open({
					type: 2,
					title:title,
					shadeClose:false,
					shade: 0.8,
					shift:2,
					area: [w, h],
					btn: ['确定', '取消'],
					content: href, //dom
					yes: function(index, layero){
	    				var iframeWin = window[layero.find('iframe')[0].name]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
	    				iframeWin.call_submit(index);
					},
					end:function(){
						$('#ajaxiframechilddate_'+index).remove();
					}
			});
		}
		//根据是否有数据设定缓存（页面缓存）
		if(!$.isEmptyObject(data)){
			var html = '<div id="ajaxiframechilddate_'+index+'" style="display:none">'+JSON.stringify(data)+'</div>';
			$('body').append(html);
		}
		// 键盘Esc键
		$(document).keydown(function(event) {
			var keycode = event.which;
			if (keycode == 27) {
				layer.close(index);
			}
		});
	};
	H.prototype.tips = function(info,dom){
		layer.tips(info,dom,{tips:[3, '#ba0dc7']});
	};
	H.prototype.error = function (info) {
		layer.msg(info, {icon: 2})
	};
	H.prototype.success = function (info) {
		layer.msg(info, {icon: 1})
	};
	H.prototype.warning = function (info) {
		layer.msg(info, {icon: 7})
	};
	H.prototype.getpath = function(){
		var strFullPath=window.document.location.href;
		var index = strFullPath.lastIndexOf("\/");
		strFullPath = strFullPath.substring(0,index+1);
		return strFullPath;
	};
	H.prototype.openwin = function(url,width,height,callback){
		let that = this;
		let modalPath = that.path.join('file://', that.getpath(), url);
		let nowwindow = that.BrowserWindow.getFocusedWindow();
		let win = new that.BrowserWindow({width:width,height:height,parent:nowwindow,modal:true})
		let winid = 'callback_'+win.id;
		win.on('close', function () { 
			that.ipcMain.removeAllListeners(winid);
			win = null;
		});
		//暂时用异步传输防止未传输完成就关闭
		that.ipcMain.on(winid, function(event, arg) {
		  	callback?callback(arg):'';
		  	event.sender.send('callback_result', true);
		});
		win.loadURL(modalPath);
		win.once('unresponsive', () => {
		  alert('抱歉界面已卡死，请关掉重启！');
		});
		win.once('ready-to-show', () => {
		  win.show();
		});
		
		/*win.webContents.on('did-finish-load', function() {
			win.webContents.send('ping', 'hahaha!');
		});*/
		/*const ipcRenderer = top.require('electron').ipcRenderer;
		ipcRenderer.send('ping', 'ping');*/
	};
	H.prototype.callbackwin = function(data,fun){
		let res = false;
		let thiswindow = this.electron.remote.getCurrentWindow();
		this.electron.ipcRenderer.send('callback_'+thiswindow.id,data);
		this.electron.ipcRenderer.on('callback_result', function(event, arg) {
		  	res = arg;
		  	fun?fun(res):'';
		});
	};
	//关闭页面
	H.prototype.closewin = function(win){
		win = !win ? this.electron.remote.getCurrentWindow() : win;
		win.close();
	}
	H.prototype.opensinglewin = function(url,width,height){
		let that = this
		let modalPath = that.path.join('file://', that.getpath(), url)
		let win = new that.BrowserWindow({width:width,height:height})
		win.on('close', function () { 
			win = null;
		})
		win.loadURL(modalPath);
		win.once('ready-to-show', () => {
		  win.show()
		})
	}
	H.prototype.openchildwin = function(url,width,height,callback){
		let that = this
		let modalPath = that.path.join('file://', that.getpath(), url)
		let win = new that.BrowserWindow({width:width,height:height})
		win.on('close', function () { 
			callback?callback():'';
			win = null;
		})
		win.loadURL(modalPath);
		win.once('ready-to-show', () => {
		  win.show()
		})
	}
	//加
	H.prototype.accAdd = function(arg1,arg2){      
		var r1,r2,m;
		try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
		try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
		m=Math.pow(10,Math.max(r1,r2))
        return (this.accMul(arg1,m)+this.accMul(arg2,m))/m
	}
	//减
	H.prototype.accSub = function(arg1,arg2){
		var r1,r2,m;
   		try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
   		try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
        m=Math.pow(10,Math.max(r1,r2))
        return (this.accMul(arg1,m)-this.accMul(arg2,m))/m
	}
	//乘
	H.prototype.accMul = function(arg1,arg2){
		var m=0,s1=arg1.toString(),s2=arg2.toString();   
	    try{m+=s1.split(".")[1].length}catch(e){}
	    try{m+=s2.split(".")[1].length}catch(e){}
	    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
	}
	//除
	H.prototype.accDiv = function(arg1,arg2){
		var t1=0,t2=0,r1,r2;
    	try{t1=arg1.toString().split(".")[1].length}catch(e){}
    	try{t2=arg2.toString().split(".")[1].length}catch(e){} 
		r1=Number(arg1.toString().replace(".",""))
		r2=Number(arg2.toString().replace(".",""))
		return (r1/r2)*Math.pow(10,t2-t1);
	}

	H.prototype.inarray = function (value, array, key) {
		let findKey = -1
		array.forEach((row, index) => {
			if (row[key] == value) findKey = index
		})
		return findKey
	}

	H.prototype.times = function(unix){
		let tm = unix?new Date(unix*1000):new Date();
		let yy = tm.getFullYear();
		let mm = tm.getMonth()<9?'0'+(tm.getMonth()+1):tm.getMonth()+1;
		let dd = tm.getDate()<10?'0'+tm.getDate():tm.getDate();
		let hh = tm.getHours()<10?'0'+tm.getHours():tm.getHours();
		let ii = tm.getMinutes()<10?'0'+tm.getMinutes():tm.getMinutes();
		let ss = tm.getSeconds()<10?'0'+tm.getSeconds():tm.getSeconds();

		return yy+'-'+mm+'-'+dd+' '+hh+':'+ii+':'+ss;
	}

	H.prototype.time = function(unix){
		let tm = unix?new Date(unix*1000):new Date();
		let yy = tm.getFullYear();
		let mm = tm.getMonth()<9?'0'+(tm.getMonth()+1):tm.getMonth()+1;
		let dd = tm.getDate()<10?'0'+tm.getDate():tm.getDate();

		return yy+'-'+mm+'-'+dd;
	}

/*********************新式页面弹窗及传参*********************/
	H.prototype.openBrowserWindow = function(url, data, options){
		let that = this;
		return new Promise((res, rej) => {
			let modalPath = that.path.join(Conf.root, url)		
			let nowwindow = that.BrowserWindow.getFocusedWindow()
			let opt = {
				width: 800,
				height: 600,
				parent: nowwindow,
				modal: true
			}
			opt = Object.assign(opt, options)
			let win = new that.BrowserWindow(opt)
			let sendId = 'send_' + win.id
			let receiveId = 'receive_' + win.id

			// 设置传参
			data = data || {}
			that.set_localStorage(sendId, data)
			win.on('close', function () { 
				// 删除缓存
				let receiveData = that.get_localStorage(receiveId)
				res(receiveData)
				that.remove_localStorage(sendId)
				that.remove_localStorage(receiveId)
				win = null
			})
			win.loadURL(modalPath)
			win.once('ready-to-show', () => {
			  win.show()
			})
		}).catch((e) => {console.log(e)})
	}
	H.prototype.closeBrowserWindow = function (data, win) {
		win = !win ? this.electron.remote.getCurrentWindow() : win
		data = data || {}
		this.set_localStorage('receive_' + win.id, data)
		win.close()
	}
	H.prototype.getDatas = function () {
		let win = this.electron.remote.getCurrentWindow()
		return this.get_localStorage('send_' + win.id)
	}

	H.prototype.ajax = function(url,data,type){	
		return new Promise((res, rej) => {
			type = type || 'post'
			layer.ready(function(){ 
				var indexload = layer.load();
				$.ajax({
					type:type,
					url:Conf.domain+url,
					data:data,
					//下面这个先不做
					beforeSend: function( xhr ) {
						xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
					},
					success:function(data){
						layer.close(indexload);
						//全局判断是否登陆未登录跳出
						if (('undefined' != typeof data.isrelogin) && 1 == data.isrelogin){
							window.location.href = Conf.root+'/index.html';
						}
						data.errno > 0?data.errno == 1000?layer.msg(data.errmsg,{icon:2,time:2000}):layer.msg('请求失败！'):res(data)
					},
					error:function(data, XMLHttpRequest, textStatus, errorThrown){  
						layer.close(indexload);
						layer.msg('网络传输失败！');
					}
				});
			});	
		}).catch((e) => {console.log(e)})
			
	};
/*********************新式页面弹窗及传参*********************/

	// 初始加载时获取数据列表存到sessionStorage
	H.prototype.sessionStorage = function(url, data, sessionName, cb){
		this.get_info_ajax(url, data, 'get', (list)=>{
			sessionName = JSON.stringify(list)
			window.sessionStorage.setItem('list', sessionName);
			cb();
		})
	}

	var Hobject = new H();
	window.H = Hobject;
	!window.RequestUrl?window.RequestUrl = Hobject.makerequest():'';
	window.Conf = _config;
}(window.layer || null,window.globalconfig || null,window.jQuery || null)